package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"strconv"

	"github.com/gin-gonic/gin"
)

type TaskService struct {
	repo repository.TaskRepository
}

func NewTaskService(repo repository.TaskRepository) *TaskService {
	return &TaskService{repo: repo}
}

func (s *TaskService) CreateTask(c *gin.Context) {
	var task model.Task
	if err := c.ShouldBindJSON(&task); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.CreateTask(&task); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, task)
}

func (s *TaskService) GetTask(c *gin.Context) {
	id := c.Param("id")
	task, err := s.repo.GetTask(id)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, task)
}

func (s *TaskService) UpdateTask(c *gin.Context) {
	id := c.Param("id")
	var task model.Task
	if err := c.ShouldBindJSON(&task); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	uintID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	task.ID = uint(uintID)

	if err := s.repo.UpdateTask(&task); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, task)
}

func (s *TaskService) DeleteTask(c *gin.Context) {
	id := c.Param("id")
	if err := s.repo.DeleteTask(id); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *TaskService) ListTasks(c *gin.Context) {
	tasks, err := s.repo.ListTasks()
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, tasks)
}

func (s *TaskService) ToggleTaskStatus(c *gin.Context) {
	id := c.Param("id")
	status := c.Query("status")
	if status == "" {
		c.JSON(400, gin.H{"error": "status parameter is required"})
		return
	}

	if err := s.repo.ToggleTaskStatus(id, status); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "status updated"})
}
